var editor = null;
var type = "";

function submitFn() {
    var param = checkParam();
    if ($.isPlainObject(param)) {
        if (type === "edit" || type === "add") {
            param.type = type;
            if (type === "edit") {
                param.id = getUrlParm("id");
            }
        } else {
            layer.msg("无法识别的操作！", fn);
            return false;
        }
        if ($(this).attr("data-val") == "saveAndPublish") {
            param.enable = 1;
        } else {
            param.enable = 0;
        }
        editFn(param);
    }

}

function editFn(param) {
    $.ajax({
        url: "/notice/back/editNotice.zb",
        type: "POST",
        dataType: "JSON",
        data: param
    }).done(function (res) {
        if (res && res.success) {
            if (param.type == "edit") {
                layer.msg(res.msg);
            } else {
                layer.msg("添加成功,即将刷新数据！", function () {
                    window.location.reload();
                })
            }
        } else {
            layer.msg(res.msg || "操作失败！", fn);
        }
    }).fail(function () {
        layer.msg("可能由于网络等原因操作失败！", fn);
    })
}

function checkParam() {
    var passTem = true;
    var param = {};
    param.title = $("#title").val().trim();
    var wangeditorContentText = editor.txt.text();
    if (param.title.trim().length <= 0) {
        $("#title").attr("data-content", "请输入公告标题").popover('show');
        passTem = false;
    } else {
        $("#title").popover("hide");
    }
    if (!wangeditorContentText) {
        $("#wangeditorContent").parent().attr("data-content", "文本不能为空").popover('show');
        passTem = false;
    } else {
        param.content = editor.txt.html();
        $("#wangeditorContent").parent().popover('hide');
    }
    if (passTem) {
        return param;
    } else {
        return false;
    }
}

function loadDefault() {
    if (getUrlParm("type") == "edit") {
        type = "edit";
        $("title").text("更新公告");
        $.ajax({
            url: "/notice/back/getNoticeById.zb",
            type: "POST",
            dataType: "JSON",
            data: {id: getUrlParm("id")}
        }).done(function (res) {
            console.log(res)
            if (res && res.success) {
                $("#title").val(res.data.title);
                editor.txt.html(res.data.content);
            }
        }).fail(function () {
            layer.msg("可能由于网络等原因加载公告失败！", fn)
        })
    } else {
        type = "add";
        $("title").text("发布公告");
    }
}

function getUrlParm(param) {
    var reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}

function fn() {
}